package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.Result;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
* @author Yoo19
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-07-03 09:36:43
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Override
    public Result login(LoginInfoVo loginInfoVo) {
        //通过手机号查询用户是否存在
        TbUser user = tbUserMapper.selectOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, loginInfoVo.getUserMobile()));
        if(user == null){
            return Result.error().setMsg("用户不存在");
        }

        //判断密码是否正确
        if(!user.getUserPass().equals(loginInfoVo.getUserPass())){
            return Result.error().setMsg("密码错误");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId())
                .compact();
        String redisKey = "token-" + user.getUserMobile();
        request.setAttribute("token",token);

        redisTemplate.opsForValue().set(redisKey,token,60, TimeUnit.MINUTES);

        user.setUserPass(null);
        user.setToken(token);
        return Result.ok().setData(user);
    }
}




